<template>
  <div class=" zy-content pb50">
    <back-level @click="close"/>
    <Card
        :title="`${$t('spareParts.PickingApplication')}`"
        class="detail-content-layout">
      <div class="searchBox search-box-layout" style="padding: 0;box-shadow: none">
        <Row :gutter="24">
          <Col span="4">
            <div>
              <p class="label">{{$t('spareParts.PartNoGoodsNameSpecification')}}</p>
              <div class="ipt">
                <Select filterable
                        v-model="searchParams.text"
                        :remote-method="remoteMethod"
                        clearable
                        @on-change="handleText"
                        :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="item of texttList"
                          :value="item.id"
                          :label="item.materielNo"
                          :key="item.id">
                    {{item.materielNo +'-'+item.goodsName +'-'+item.specification + '-' + item.warehouseName}}
                  </Option>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('spareParts.company')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.companyName"
                        @on-change="changeCompany"
                        clearable :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="(item,index) of tagList" :value="item.name" :label="item.name"  :key="index"/>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('common.Warehouse')}}</p>
              <div class="ipt">
                <Select v-model="searchParams.warehouseId"
                        clearable
                        disabled
                        :placeholder="`${$t('common.selectInfo')}`">
                  <Option v-for="(item,index) of warehouseList"
                          :value="item.id"
                          :label="item.backupName"
                          :key="index"/>
                </Select>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label">{{$t('common.UserFactory')}}</p>
              <div class="ipt">
                <Cascader
                    v-model="searchParams.orgId"
                    :data="orgList"
                    :transfer="true"
                    @on-change="handleCasChange"
                ></Cascader>
              </div>
            </div>
          </Col>
          <Col span="4">
            <div>
              <p class="label hide-label">--</p>
              <div class="ipt">
                <Button class="search-btn" type="primary" v-if="$route.query.status !=='detail'" @click="addTable()">{{$t('保存添加')}}</Button>
                <Button
                    class="reset-btn"
                    @click="changeNum()"
                >{{ $t('common.reset') }}
                </Button>
              </div>
            </div>
          </Col>
        </Row>
      </div>

      <div class="basic-info tableContent" style="border: none">
        <Table
            class="resizable-table" border @on-column-width-resize="onColumnWidthResize"
            height="700"
            :columns="tableColumns"
            :data="tablelist">
          <template slot-scope="{ row,i }" slot="applyNum">
            <span v-if="row.manageType === 1">1</span>
            <span v-else>
              <Input type="number"
                     v-model="row.applyNum"
                    :disabled="$route.query.status ==='detail'"
                     @on-change="applyNumchange(row)"/>
              </span>
          </template>
          <template slot-scope="{ row }" slot="remark">
            <Input  :disabled="$route.query.status ==='detail'" v-model="row.remark"  @on-change="remarkNumchange(row)"/>
          </template>
          <template slot-scope="{ row }" slot="action">
            <span class="operationBtn" @click="delRow(row)"><i class="iconfont zy-common-shanchu"></i>{{$t('common.Delete')}}</span>
          </template>
        </Table>
      </div>
      <!--    <div class="pageWrap">-->
      <!--      <Page :total="total"-->
      <!--            :page-size="pageSize"-->
      <!--            :page-size-opts="pageSizeOption"-->
      <!--            :current="pageNum"-->
      <!--            @on-change="changePageNum"-->
      <!--            @on-page-size-change="changePageSize"-->
      <!--            show-sizer show-total />-->
      <!--    </div>-->

    </Card>
    <bottom-handle-wrap  v-if="$route.query.status !=='detail'">
      <Button @click.prevent="close">{{$t('common.Cancle')}}</Button>
      <Button type="primary"  :loading="saveloading"   @click.prevent="handleSave">{{$t('common.Save')}}</Button>
      <Button type="primary"   @click.prevent="handleSumit">{{$t('common.submit')}}</Button>
    </bottom-handle-wrap>
  </div>
</template>

<script>
import recursion from "@/util/recursion";
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
  name: "recipientsModule",
    mixins:[toggleTableOperation],
  data(){
    return  {
      saveloading:false,
      sumitloading:false,
      rowremark:'',
      rowapplyNum:'',
      pageSizeOption: [10,20,30,40],
      pageNum:1,
      pageSize:10,
      total:0,
      texttList:[],
      searchParams:{},
      orgList:[],
      warehouseList:[],
      tagList: [{id: '', name: '全部'}],
      tablelist:[],
      tableColumns:[
        {
          title: `${this.$t('spareParts.PartNo')}`,
          key: 'materielNo',
          minWidth: 100,
          align: "center",
            resizable: true
        },
        {
          title: `${this.$t('common.GoodsName')}`,
          key: 'goodsName',
          minWidth: 150,
          align: "center",
            resizable: true
        },
        {
          title: `${this.$t('spareParts.Specification')}`,
          key: 'specification',
          minWidth: 150,
          align: 'center',
            resizable: true
        },
        {
          title: `${this.$t('spareParts.Warehouse')}`,
          key: 'warehouseName',
          minWidth: 150,
          align: "center",
            resizable: true
        },
        {
           title: `${this.$t('spareParts.InventoryQuantity')}`,
          key: 'safeStock',
          minWidth: 150,
          align: "center",
            resizable: true
        },
        {
          title: `${this.$t('已申请数量')}`,
          key: 'allApplyNum',
          minWidth: 200,
          align: "center",
            resizable: true
        },
        {
          title: `${this.$t('可申请数量')}`,
          key: 'virtualInStock',
          minWidth: 200,
          align: "center",
            resizable: true
        },
        {
          title: `${this.$t('common.ApplicationQuantit')}`,
          key: 'applyNum',
          slot: "applyNum",
          minWidth: 200,
          align: "center",
            resizable: true
        },
        {
          title: `${this.$t('spareParts.UserFactory')}`,
          key: 'factoryArea',
          minWidth: 150,
          align: "center",
            resizable: true
        },
        {
          title: `${this.$t('spareParts.UserReson')}`,
          key: 'remark',
          minWidth: 200,
          slot: "remark",
          align: "center",
            resizable: true
        },
        {
          title: `${ this.$t('common.operation') }`,
          slot: "action",
          fixed:'right',
          minWidth: 150,
          align: "center"
        }
      ],
      factoryAreaName:'',
      targetObj:{},
      companyIdinfo:'',
      companyNameinfo:'',
      idNum:0,
    }
  },
  mounted() {

      this.getColumnWidth(this.tableColumns)

    this.getCompanyList()
    this.getOrgList()
    if (this.$route.query.status === 'edit' || this.$route.query.status ==='detail'){
      this.searchList()
      if (this.$route.query.status ==='detail'){
        this.tableColumns = this.tableColumns.splice(0,this.tableColumns.length -1)
      }
    }
  },
  methods:{
    applyNumchange(row){
      this.tablelist.forEach(val=>{
        if (val.id === row.id){
          val.applyNum = Number(row.applyNum)
        }
      })
    },
    remarkNumchange(row){
      this.tablelist.forEach(val=>{
        if (val.id === row.id){
          val.remark = row.remark
        }
      })
    },
    addTable(){
      this.idNum++;
      if (!this.searchParams.text){
        this.$Message.warning(({content:this.$t('请输入料号'),duration:6,closable:true}));
        return
      }
      if (!(this.searchParams.orgId && this.searchParams.orgId.length)){
        this.$Message.warning(({content:this.$t('请选择厂区'),duration:6,closable:true}));
        return
      }
      if (this.targetObj){
        this.targetObj.factoryArea = this.factoryAreaName
        this.targetObj.factoryArea = this.factoryAreaName
        this.targetObj.factoryAreaId = this.searchParams.factoryAreaId
        // this.targetObj.companyName = this.searchParams.companyName
        this.targetObj.warehouseId = this.searchParams.warehouseId
        this.targetObj.warehouseName = this.warehouseList.find(val=>val.id === this.searchParams.warehouseId).backupName
      }
      const obj = {
        id:this.idNum,
        tarGetid:this.targetObj.materielNo,
        // standingBookId:this.targetObj.id,
        materielNo:this.targetObj.materielNo,
        goodsName:this.targetObj.goodsName,
        specification:this.targetObj.specification,
        warehouseId:this.targetObj.warehouseId,
        warehouseName:this.targetObj.warehouseName,
        safeStock:this.targetObj.quantityInStock,
        factoryArea:this.targetObj.factoryArea,
        factoryAreaId:this.targetObj.factoryAreaId,
        manageType:this.targetObj.manageType,
        applyNum:'',
        remark:'',
        virtualInStock:this.targetObj.virtualInStock,
        allApplyNum:this.targetObj.allApplyNum,
      }
      if (this.targetObj.manageType === 1){
          obj.applyNum = 1
      }
      this.tablelist.push(obj)
      this.searchParams = {}
      this.texttList = []
    },
    handleText(val){
      this.targetObj ={}
      if (val){
        this.targetObj = this.texttList.find(item=>item.id === val)
        if (this.targetObj.companyName){
          this.companyNameinfo = this.targetObj.companyName
          this.companyIdinfo = this.tagList.find(item => item.name === this.targetObj.companyName).id
          this.getwarehouseList(this.companyIdinfo)
        }
      }
    },
    remoteMethod(text){
      // let materielNos = ''
      // if (this.tablelist && this.tablelist.length){
      //   materielNos = this.tablelist.map(val=>val.materielNo).join(',')
      //  }
      this.axios({
        method: 'get',
        url: '/dms/applyUse/querySearch',
        params: {
          text
        }
      }).then(res => {
        if(res.code === 200){
          this.texttList = res.data
          this.texttList.forEach(val=>val.id = val.materielNo + val.warehouseName)
        }else{
          this.$Message.warning(({content:res.msg,duration:6,closable:true}));
        }
      })
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val){
      this.pageNum = val;
      this.searchList();
    },
    handleSumit(){
      // this.sumitloading = true
      if (!(this.tablelist && this.tablelist.length)){
        this.$Message.error(({content:'请添加数据!',duration:6,closable:true}));
        return
      }
      let url = '/dms/applyUse/add'
      if (this.$route.query.status === 'edit'){
        url = '/dms/applyUse/edit'
      }
      const data = {
        companyId:this.companyIdinfo,
        companyName:this.companyNameinfo,
        details:this.tablelist
      }
      if (this.$route.query.status === 'edit'){
        data.companyId = this.$route.query.companyId
        data.companyName = this.$route.query.companyName
        data.id = this.$route.query.id
      }
      this.axios({
        method: 'post',
        url,
        data
      }).then(res=>{
        if (res.code == 200){
          this.axios({
            method: 'get',
            url: '/dms/applyUse/applyStatus',
            params: {
              id:res.data.id,
              applyStatus:1
            }
          }).then(respon=>{
            if (res.code == 200){
              this.close()
            }else{
              this.$Message.warning(({content:res.msg,duration:6,closable:true}));
            }
            // this.sumitloading = false
          })
        }else{
          this.$Message.warning(({content:res.msg,duration:6,closable:true}));
        }
      })
    },
    handleSave(){
      this.saveloading = true
      if (!(this.tablelist && this.tablelist.length)){
        this.$Message.error(({content:'请添加数据!',duration:6,closable:true}));
        return
      }

      let url = '/dms/applyUse/add'
      if (this.$route.query.status === 'edit'){
        url = '/dms/applyUse/edit'
      }

      const data = {
        companyId:this.companyIdinfo,
        companyName:this.companyNameinfo,
        details:this.tablelist
      }
      if (this.$route.query.status === 'edit'){
        data.companyId = this.$route.query.companyId
        data.companyName = this.$route.query.companyName
        data.id = this.$route.query.id
      }

      this.axios({
        method: 'post',
        url,
        data
      }).then(res=>{
        if (res.code == 200){
          this.close()
        }else{
          this.$Message.warning(({content:res.msg,duration:6,closable:true}));
        }
        this.saveloading = false
      })
    },
    delRow(row){
      this.tablelist = this.tablelist.filter(val=>val.id !== row.id)
    },
    changeNum(){
      this.pageNum = 1;
      this.searchList();
    },
    searchList(){
      let params = {
        id:this.$route.query.id
      }
      this.axios({
        method: 'get',
        url: '/dms/applyUse/query',
        params: params
      }).then(res => {
        if(res.code === 200){
          if (res.data.details){
            if (res.data.details && res.data.details.length){
                res.data.details.forEach(val=>{
                val.tarGetid = val.standingBookId
              })
            }
            this.tablelist = res.data.details
          }else {
            this.tablelist = []
          }
        }else{
          this.$Message.warning(({content:res.msg,duration:6,closable:true}));
        }
      })
    },
    close() {
      this.$router.go(-1)
    },
    //公司列表
    getCompanyList() {
      this.axios({
        method: 'get',
        url: '/basic/company/getCompanyListByUser',
        params: {}
      }).then(res => {
        if(res.code === 200){
          let arr = res.data.map(item => {
            return {
              ...item,
              id: item.id
            }
          })
          this.tagList = [...this.tagList,...arr]
        }else{
          this.$Message.warning(({content:res.msg,duration:6,closable:true}));
        }
      })
    },
    fiflterLine(dataList){
      dataList.forEach(val=>{
        if (val.level === 3){
           val.children = []
        }
        if (val.children && val.children.length){
          // const flag = val.children.some(item => item.label.includes('Line'))
          // if (flag){
          //   val.children = val.children.filter(list => !list.label.includes('Line'))
          // }
          this.fiflterLine(val.children)
        }
      })
      return dataList
    },
    getOrgList() {
      this.axios({
        method: 'get',
        url: '/basic/organization/findListByToken',
        params: {}
      }).then(res => {
        if(res.code === 200){
          const obj ={
            label: 'name',
            value: 'id',
            children: 'children'
          }
          const dataArr = recursion.convertTree(res.data, obj)
          this.orgList = this.fiflterLine(dataArr)
        }else{
          this.$Message.warning(({content:res.msg,duration:6,closable:true}));
        }
      })
    },
    handleCasChange(val, selectedData) {
      const arr = selectedData.map(val=>val.label)
      this.factoryAreaName = arr[arr.length-1]
      this.searchParams.factoryAreaId = val[val.length-1]
      // this.searchParams.orgName = selectedData[selectedData.length-1].label
    },
    changeCompany(val){
      if (val){
        this.companyNameinfo = val
        this.companyIdinfo = this.tagList.find(item => item.name == val).id
        this.getwarehouseList(this.companyIdinfo)
      }else {
        this.searchParams.warehouseName = ''
        this.warehouseList = []
      }
    },
    getwarehouseList(companyId){
      this.searchParams.warehouseId = ''
      this.warehouseList = []
      this.axios({
        method: 'post',
        url: '/dms/dmsBackupConfig/queryBackupsByCompany',
        data: {
          companyId
        }
      }).then(res=>{
        if (res.data && res.data.length){
          this.warehouseList = res.data
          this.$nextTick(()=>{
            this.searchParams = {
              ...this.searchParams,
              companyName:this.targetObj.companyName,
              warehouseName:this.targetObj.warehouseName,
              warehouseId:this.targetObj.backupConfigId
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
/deep/ .ivu-input{
  border: 1px solid #dcdee2 !important;
}
.picking{
  height: 100%;
  position: relative;
  .btnList{
    position: absolute;
    bottom: 20px;
    left: 40%;
    .ivu-btn{
      margin: 0 5px;
    }
  }
}
.ivu-card-body{
  padding: 0;
}
.basic-info {
  padding: 16px;
  border-bottom: 1px solid #e8eaec;
  .search-form {
    padding: 0;
    .ivu-form-item{
      margin: 0;
    }
  }
}
</style>
